<template>
  <!-- 新建任务类型弹框 -->
  <div class="new-project-type-dialog">
    <el-dialog :title="$t('projectManage.taskType.new.title')" :visible.sync="dialogVisible" width="500px" @close="handleClickCancel">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" @submit.native.prevent>
        <el-form-item :label="$t('projectManage.taskType.new.label1')" prop="templateName">
          <el-input v-model="form.templateName" :placeholder="$t('projectManage.taskType.new.placeholder1')"></el-input>
        </el-form-item>

        <el-form-item>
          <ul class="state-color">
            <li v-for="color in typeColor" :key="color" @click="form.color = color" :style="{ background: color }">
              <i class="el-icon-check" v-if="color === form.color"></i>
            </li>
          </ul>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClickCancel">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="handleClickSure(ruleFormRef)" :loading="saveLoading">{{ $t('common.base.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { defineComponent, ref, reactive, toRefs, nextTick } from 'vue';

import { typeColor } from '@src/modules/setting/projectManage/utils/index.js';

import i18n from '@src/locales';

export default defineComponent({
  name: 'new-project-type-dialog',

  emits: ['submitSave'],

  setup(props, { emit }) {
    const dialogVisible = ref(false);
    const ruleFormRef = ref();

    const state = reactive({
      form: {
        templateName: '',
        color: 'rgb(115,127,124)',
      },
      rules: {
        templateName: [
          { required: true, message: i18n.t('projectManage.taskType.new.typeTip'), trigger: 'blur' },
          { max: 20, message: i18n.t('projectManage.taskType.new.typeTip1'), trigger: 'blur' },
        ],
      },
      saveLoading: false,
    });

    // 点击确定
    const handleClickSure = async formEl => {
      if (!formEl) return;

      await formEl.validate((valid, fields) => {
        if (!valid) return;

        state.saveLoading = true;

        emit('submitSave', state.form);
      });
    };

    // 重置表单
    const resetField = () => {
      state.form.color = 'rgb(115,127,124)';
      state.saveLoading = false;

      nextTick(() => {
        ruleFormRef.value.resetFields();
      });
    };

    // 点击取消 or 关闭
    const handleClickCancel = () => {
      if (!ruleFormRef.value) return;

      dialogVisible.value = false;
      resetField();
    };

    return {
      dialogVisible,
      ruleFormRef,
      typeColor,
      ...toRefs(state),
      handleClickSure,
      resetField,
      handleClickCancel,
    };
  },
});
</script>

<style lang="scss" scoped>
@import './color.scss';
</style>
